//
//  PHUserInfo.m
//  PhnixHome
//
//  Created by Levy Xu on 2018/1/3.
//  Copyright © 2018年 Levy Xu. All rights reserved.
//

#import "PHUserInfo.h"
#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>

@implementation PHUserInfo

-(NSString *)genderString {
    if (KIsBlankString(_sex))
        return @"";
    
    if ([_sex isEqualToString:@"0"]) {
        return NSLocalizedString(@"Male", nil);
    } else if ([_sex isEqualToString:@"1"]) {
        return NSLocalizedString(@"Female", nil);
    }
    return @"";
}

-(NSString *)account {
    return KIsBlankString(_phone) ? _email : _phone;
}

-(NSMutableDictionary *)modifyDict {
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    [result setObject:KNotNilString(_user_name) forKey:@"user_name"];
    [result setObject:KNotNilString(_nick_name) forKey:@"nick_name"];
    [result setObject:KNotNilString(_sex) forKey:@"sex"];
    [result setObject:KNotNilString(_address) forKey:@"address"];
    [result setObject:KNotNilString(_birthday) forKey:@"birthday"];
    return result;
}

@end

NSString *const kUserInfoChangedNotification = @"kUserInfoChangedNotification";

@implementation GlobalUser

SingletonM(GlobalUser, )

- (void)logUser {
    [CrashlyticsKit setUserIdentifier:_info.user_id];
    [CrashlyticsKit setUserEmail:[_info account]];
    if (_info.nick_name) {
        [CrashlyticsKit setUserName:_info.nick_name];
    } else if (_info.user_name) {
        [CrashlyticsKit setUserName:_info.user_name];
    }
}


-(void)getUserInfo:(BOOL)animated finish:(FinishBlock)finish {
    WS(ws);
    if (animated) [KKHUD showLoading:NSLocalizedString(@"tips_waiting", nil)];
    [[NetUtils JSONManager] GET:@"user/getUserInfo.json" parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        if (result.is_result_suc) {
            if (animated) [KKHUD showSucceed:NSLocalizedString(@"tips_success", nil)];
            
            ws.info = [PHUserInfo mj_objectWithKeyValues:result.object_result];
            
            [NDSUD setObject:[ws.info account] forKey:@"kLastLoginUserName"];
            
            [NNCDC postNotificationName:kUserInfoChangedNotification object:nil];
            
            //微信登录上传用户信息
            if ([NDSUD objectForKey:@"WXSaveUserInfo"]) {
                if (!ws.info.img && !ws.info.nick_name && !ws.info.sex) {
                    NSDictionary *wxinfo = [NDSUD objectForKey:@"WXSaveUserInfo"];
                    NSInteger sex = [wxinfo[@"sex"] integerValue];
                    NSString *sexString = @"";
                    if (sex == 2) {
                        sexString = @"1";
                    } else if (sex == 1) {
                        sexString = @"0";
                    }
                    NSDictionary *dict = @{ @"sex": sexString, @"img": wxinfo[@"headimgurl"], @"nick_name": wxinfo[@"nickname"] };
                    [self modify:dict];
                }
                [NDSUD removeObjectForKey:@"WXSaveUserInfo"];
            }
            
            [ws logUser];
            
            !finish ?: finish(YES);
        } else {
            if (animated) [KKHUD showError:result.error_msg];
            !finish ?: finish(NO);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        LOG(@"error %@",error.description);
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
        !finish ?: finish(NO);
    }];
}

-(void)uploadThirdAvatar:(NSString *)urlString {
    LOG(@"urlString %@", urlString);
    if (KIsBlankString(urlString)) {
        return;
    }
    WS(ws);
    NSURL *url = [NSURL URLWithString:urlString];
    SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
    [downloader downloadImageWithURL:url options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        LOG(@"progerss %f, targetURL %@", receivedSize / (float)expectedSize, targetURL);
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        LOG(@"finished %@ data %@ error %@",image, data, error);
        
        [ws uploadAvatar:image];
    }];
}

-(void)uploadAvatar:(UIImage *)image {
    
    UIImage *my_image = image;
    if (my_image.size.width > 300) {
        my_image = [image qmui_imageResizedInLimitedSize:CGSizeMake(300, 300)];
    }
    
    LOG(@"my_image %@",my_image);
    
    NSData *data = UIImageJPEGRepresentation(my_image, 1.0);
    
    NSString *avatarPath = [DOC_DIR stringByAppendingPathComponent:@"avatars"];
    [FM createDirectoryAtPath:avatarPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString *fileName = [NSString stringWithFormat:@"%@.jpg", GGlobalUser.info.user_id];
    NSString *avatarFile = [avatarPath stringByAppendingPathComponent:fileName];
    BOOL result = [data writeToFile:avatarFile atomically:YES];
    if (!result) {
        LOG(@"save failed");
    }
    
    WS(ws);
    [KKHUD showLoading:NSLocalizedString(@"tips_waiting", nil)];
    
    NSURL *baseUrl = [NSURL URLWithString:kBaseURL];
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:APP_DELEGATE.token.token forHTTPHeaderField:@"x-token"];
    LOG(@"header %@",manager.requestSerializer.HTTPRequestHeaders);
    
    [manager POST:@"user/uploadImg.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"head_icon" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSInteger value = (NSInteger)(100 * uploadProgress.fractionCompleted);
        [NSThread mainTask:^{
            [KKHUD showLoading:[NSLocalizedString(@"tips_waiting", nil) stringByAppendingFormat:@"(%d%%)", (int)value]];
        }];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        LOG(@"responseObject %@",responseObject);
        
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        if (result.is_result_suc) {
            [KKHUD showSucceed:NSLocalizedString(@"tips_success", nil)];
            
            [ws getUserInfo:NO finish:^(BOOL success) {
                ;
            }];
        } else {
            [KKHUD showError:result.error_msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LOG(@"error %@",error.description);
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
    }];
}

-(void)modify:(NSDictionary *)dict {
    NSMutableDictionary *user = _info.modifyDict;
    [user addEntriesFromDictionary:dict];
    
    LOG(@"user %@",user);
    WS(ws);
    [KKHUD showLoading:NSLocalizedString(@"tips_waiting", nil)];
    [[NetUtils JSONManager] POST:@"user/updateUser.json" parameters:@{ @"user": user } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        CommonResult *result = [CommonResult mj_objectWithKeyValues:[responseObject mj_JSONObject]];
        LOG(@"responseObject %@",responseObject);
        if (result.is_result_suc) {
            [KKHUD showSucceed:NSLocalizedString(@"tips_success", nil)];
            
            [ws getUserInfo:NO finish:nil];
        } else {
            [KKHUD showError:result.error_msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        LOG(@"error %@",error.description);
        [KKHUD showError:NSLocalizedString(@"tips_network_error", nil)];
    }];
}

@end
